package com.partsoft.utils;

import java.util.Locale;

/**
 * 区域设置帮助类
 * 
 * @author neeker
 * 
 */
public abstract class LocaleUtils {

	private static final ThreadLocal<LocaleContext> localeContextHolder = new ThreadLocal<LocaleContext>();

	private static final ThreadLocal<LocaleContext> inheritableLocaleContextHolder = new InheritableThreadLocal<LocaleContext>();

	/**
	 * 重设当前线程的区域上下文
	 */
	public static void resetLocaleContext() {
		localeContextHolder.set(null);
		inheritableLocaleContextHolder.set(null);
	}

	/**
	 * 设置当前区域上下文
	 * 
	 * @param localeContext
	 */
	public static void setLocaleContext(LocaleContext localeContext) {
		setLocaleContext(localeContext, false);
	}

	/**
	 * 设置当前区域上下文
	 * 
	 * @param localeContext
	 * @param inheritable
	 *            如果为true则使用线程继承方式
	 */
	public static void setLocaleContext(LocaleContext localeContext, boolean inheritable) {
		if (inheritable) {
			inheritableLocaleContextHolder.set(localeContext);
			localeContextHolder.set(null);
		} else {
			localeContextHolder.set(localeContext);
			inheritableLocaleContextHolder.set(null);
		}
	}

	/**
	 * 获取区域上下文
	 * 
	 * @return
	 */
	public static LocaleContext getLocaleContext() {
		LocaleContext localeContext = (LocaleContext) localeContextHolder.get();
		if (localeContext == null) {
			localeContext = (LocaleContext) inheritableLocaleContextHolder.get();
		}
		return localeContext;
	}

	public static void setLocale(Locale locale) {
		setLocale(locale, false);
	}

	/**
	 * 设置当前区域,同时设置ZK
	 * 
	 * @param locale
	 * @param inheritable
	 *            如果是，则使用线程继承方式
	 */
	public static void setLocale(Locale locale, boolean inheritable) {
		LocaleContext localeContext = (locale != null ? new SimpleLocaleContext(locale) : null);
		setLocaleContext(localeContext, inheritable);
	}

	/**
	 * 获取当前区域语言 同时同步ZK
	 * 
	 * @return
	 */
	public static Locale getLocale() {
		LocaleContext localeContext = getLocaleContext();
		Locale currentLocale = (localeContext != null ? localeContext.getLocale() : Locale.CHINA);
		return currentLocale;
	}

	public interface LocaleContext {
		Locale getLocale();
	}

	public static class SimpleLocaleContext implements LocaleContext {

		private final Locale locale;

		public SimpleLocaleContext(Locale locale) {
			Assert.notNull(locale, "Locale must not be null");
			this.locale = locale;
		}

		public Locale getLocale() {
			return this.locale;
		}

		public String toString() {
			return this.locale.toString();
		}
	}

}
